package com.wellview.template.share;

import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.JavascriptInterface;

import com.alibaba.sdk.android.push.CommonCallback;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebView;
import com.wellview.template.App;
import com.wellview.template.BaseActivity;
import com.wellview.template.Constant;
import com.wellview.template.logger.Logger;
import com.wellview.template.modle.JSBehavior;
import com.wellview.template.utils.EventCenter;
import com.wellview.template.utils.ToastUtils;
import com.wellview.template.utils.Utils;
import com.wellview.template.view.MainActivity;
import com.wellview.template.view.SelectPhotoActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * Created by Administrator on 2017/12/5 0005.
 */

public class AuthJavaScriptAccept implements PlatformActionListener {
    private String TAG = getClass().getSimpleName();
    private static final int MSG_AUTH_CANCEL = 2;
    private static final int MSG_AUTH_ERROR = 3;
    private static final int MSG_AUTH_COMPLETE = 4;
    private static final int MSG_SHARE_DELEY = 5;
    private BaseActivity activity;
    private JSBehavior behavior;
    private String extra = "";

    public AuthJavaScriptAccept(BaseActivity context, JSBehavior jsBehavior) {
        this.activity = context;
        EventBus.getDefault().register(this);
        this.behavior = jsBehavior;
    }
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            handleMsg(msg);
        }
    };

    private void handleMsg(Message msg) {
        JSONObject jsonObject = new JSONObject();
        switch (msg.what) {
            case MSG_AUTH_CANCEL: {
                //取消授权
//                ToastUtils.showToast(,R.string.auth_cancel);
                try {
                    jsonObject.put("state", "" + MSG_AUTH_CANCEL);
                } catch (Exception e) {
                    e.printStackTrace();
                    Logger.e(TAG, "error " + e.getMessage());
                }
            }
            break;
            case MSG_AUTH_ERROR: {
                //授权失败
//                ToastUtils.showToast(context,R.string.auth_error);
                try {
                    jsonObject.put("state", "" + MSG_AUTH_ERROR);
                } catch (Exception e) {
                    e.printStackTrace();
                    Logger.e(TAG, "error " + e.getMessage());
                }
            }
            break;
            case MSG_AUTH_COMPLETE: {
                //授权成功
//                showToast(R.string.auth_complete);
                Object[] objs = (Object[]) msg.obj;
                String platform = (String) objs[0];
                HashMap<String, Object> res = (HashMap<String, Object>) objs[1];
                PlatformDb db = (PlatformDb) objs[2];
                Logger.i(TAG, platform + "res: " + res.toString());
                Logger.i(TAG, platform + "userIcon" + db.getUserIcon());
                try {
                    jsonObject.put("state", "" + MSG_AUTH_COMPLETE);
                    jsonObject.put("userName", db.getUserName());
                    jsonObject.put("userIcon", db.getUserIcon());
                    jsonObject.put("userGender", db.getUserGender());
                    jsonObject.put("userId", db.getUserId());
                    jsonObject.put("expiresIn", db.getExpiresIn());
                    jsonObject.put("expiresTime", db.getExpiresTime());
                    jsonObject.put("token", db.getToken());
                    jsonObject.put("device_id", Utils.getPhoneSign());
                    jsonObject.put("'gender",res.get("gender"));
//                    jsonObject.put("extraValue", res.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                    Logger.e(TAG, "error " + e.getMessage());
                }
//                sendToJsWithParam(jsonObject.toString());
                sendToJsWithParamWithFunction(jsonObject.toString(),Constant.JS_FUNCTION_LOGINRESULT);
//                if (signupListener != null && signupListener.onSignin(platform, res)) {
//                    SignupPage signupPage = new SignupPage();
//                    signupPage.setOnLoginListener(signupListener);
//                    signupPage.setPlatform(platform);
//                    signupPage.show(activity, null);
//                }
            }
            break;
            case MSG_SHARE_DELEY:
                behavior.handleFunction(JSBehavior.ACTION_SHARE);
                break;
        }
    }

    @JavascriptInterface
    public void actionThridLogin(String platform) {
        Logger.i(TAG, "actionThridLogin : " + platform);
        if (TextUtils.isEmpty(platform)) {
            ToastUtils.showToast(activity, "参数错误");
            return;
        }
        String platform_name = "";
        try {
            JSONObject logJson = new JSONObject(platform);
            platform_name = logJson.optString("platform_name");
        } catch (Exception e) {
            ToastUtils.showToast(activity, "参数错误");
            return;
        }
        if (TextUtils.isEmpty(platform_name)) {
            ToastUtils.showToast(activity, "参数错误");
            return;
        }
        switch (platform_name) {
            case "WeChat":
                Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
                authorize(wechat);
                break;
            case "Sina":
                Platform sina = ShareSDK.getPlatform(SinaWeibo.NAME);
                authorize(sina);
                break;
            case "QQ":
                Platform qq = ShareSDK.getPlatform(QQ.NAME);
                authorize(qq);
                break;
            default:
                break;
        }
    }

    @JavascriptInterface
    public void actionSelectUserAvanter(String msg){
        Log.i(TAG,"actionSelectUserAvanter " + msg);
        if ("undefined".equals(msg)){
            ToastUtils.showToast(activity,"参数错误");
            return;
        }
        this.extra = msg;
        Intent intent = new Intent();
        intent.putExtra("extra",msg);
        intent.setClass(activity, SelectPhotoActivity.class);
        activity.startActivity(intent);
    }


    @JavascriptInterface
    public synchronized void actionThridShare(String shareMsg) {
        Logger.i(TAG, "actionThridShare : " + shareMsg);
        if (TextUtils.isEmpty(shareMsg)){
            ToastUtils.showToast(activity, "参数错误");
            return;
        }
        try {
            JSONObject shareJson = new JSONObject(shareMsg);
            String title = shareJson.optString("title");
            String imageUrl = shareJson.optString("image");
            String text = shareJson.optString("message");
            String url = shareJson.optString("url");
            String id = shareJson.optString("id");
            Logger.i(TAG,"set share msg ==>"+"title: "+title+"\n"+
                            "imageUrl: "+imageUrl+"\n"+
                            "text: "+text+"\n"+
                            "url: "+url+"\n"+
                            "id: "+id+"\n"
            );
            if (TextUtils.isEmpty(text)){
                text = title;
            }
//            imageUrl = "http://g.hiphotos.baidu.com/image/pic/item/c8ea15ce36d3d539f09733493187e950342ab095.jpg";
//            url = "https://www.baidu.com";
            ResourcesManager.getInstace(App.getInstance()).setImageUrl(imageUrl);
            ResourcesManager.getInstace(App.getInstance()).setFilePath(imageUrl);
            ResourcesManager.getInstace(App.getInstance()).setImagePath(imageUrl);
            ResourcesManager.getInstace(App.getInstance()).setTitle(title);
            ResourcesManager.getInstace(App.getInstance()).setText(text);
//            ResourcesManager.getInstace(App.getInstance()).setUrl(url);
            ResourcesManager.getInstace(App.getInstance()).setUrl(url);
            ResourcesManager.getInstace(App.getInstance()).setTitleUrl(url);
            handler.sendEmptyMessageDelayed(MSG_SHARE_DELEY,200);
        } catch (JSONException e) {
            ToastUtils.showToast(activity, "参数错误 : " + e.getMessage());
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public synchronized void onWebLoginSuccessResult(String msg){
        if (TextUtils.isEmpty(msg)|| "null".equals(msg)){
            ToastUtils.showToast(activity, "登录失败");
            return;
        }
        try {//
            JSONObject loginJson = new JSONObject(msg);
            String account = loginJson.optString("account");
            if (TextUtils.isEmpty(account)){
                ToastUtils.showToast(activity, "账号为空");
                return;
            }
            App.getInstance().getCloudPushService().bindAccount(account, new CommonCallback() {
                @Override
                public void onSuccess(String s) {
                    Logger.e(TAG," 阿里云绑定用户账号 ：状态 Success : MSG"+s);
                }

                @Override
                public void onFailed(String s, String s1) {
                    Logger.e(TAG," 阿里云绑定用户账号 ：状态 Failed : MSGs " + s + " MSGs1 : " + s1);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
            ToastUtils.showToast(activity, "登录失败,参数错误");
        }
    }

    @JavascriptInterface
    public synchronized void  onWebLogoutSuccessResult(String msg){
        Logger.i(TAG,"onWebLogoutSuccessResult"+msg);
        if (TextUtils.isEmpty(msg)|| "null".equals(msg)){
            ToastUtils.showToast(activity, "参数错误");
            return;
        }
        try {
            JSONObject logoutJson = new JSONObject(msg);
            String account = logoutJson.optString("account");
            if (TextUtils.isEmpty(account)){
                ToastUtils.showToast(activity, "账号为空");
                return;
            }
            App.getInstance().getCloudPushService().unbindAccount(new CommonCallback() {
                @Override
                public void onSuccess(String s) {
                    Logger.e(TAG," 阿里云解绑用户账号 ：状态 Success : MSG"+s);
                }

                @Override
                public void onFailed(String s, String s1) {
                    Logger.e(TAG," 阿里云解绑用户账号 ：状态 Failed : MSGs " + s + " MSGs1 : " + s1);
                }
            });
        }catch (Exception e){
            e.printStackTrace();
            ToastUtils.showToast(activity, "登录失败,参数错误");
        }
    }


    /**
     * 登录 授权
     *
     * @param platform
     */
    private void authorize(Platform platform) {
        if (platform == null) {
            Logger.i(TAG, "platform is null ");
            return;
        }
//        if (platform.isAuthValid()) {
//            platform.removeAccount(true);
//            return;
//        }
        platform.removeAccount(true);
        platform.setPlatformActionListener(this);
        //关闭SSO授权
        platform.SSOSetting(false);
        platform.showUser(null);
    }

    public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
        Logger.i(TAG, "platform:" + platform.toString() + "action: " + action);
        Logger.i(TAG, "platform.getDb().getUserId():" + platform.getDb().getUserId());
        Logger.i(TAG, "platform.getDb().getUserId():" + platform.getDb().getUserIcon());
        Logger.i(TAG, "platform.getDb().getUserId():" + platform.getDb().getUserGender());
        Logger.i(TAG, "platform.getDb().getUserId():" + platform.getDb().getUserName());
        if (action == Platform.ACTION_USER_INFOR) {
            Message msg = new Message();
            msg.what = MSG_AUTH_COMPLETE;
            msg.obj = new Object[]{platform.getName(), res, platform.getDb()};
            handler.sendMessage(msg);
        }
    }

    public void onError(Platform platform, int action, Throwable t) {
        Logger.i(TAG, "platform:" + platform.toString() + "action: " + action);

        if (action == Platform.ACTION_USER_INFOR) {
            handler.sendEmptyMessage(MSG_AUTH_ERROR);
        }
        t.printStackTrace();
    }

    public void onCancel(Platform platform, int action) {
        Logger.i(TAG, "platform:" + platform.toString() + "action: " + action);
        Logger.i(TAG, "platform.getDb().onCancel():" + platform.getDb().getUserId());
        Logger.i(TAG, "platform.getDb().onCancel():" + platform.getDb().getUserIcon());
        Logger.i(TAG, "platform.getDb().onCancel():" + platform.getDb().getUserGender());
        Logger.i(TAG, "platform.getDb().onCancel():" + platform.getDb().getUserName());
        if (action == Platform.ACTION_USER_INFOR) {
            handler.sendEmptyMessage(MSG_AUTH_CANCEL);
        }
    }
    // Android版本变量
    final int version = Build.VERSION.SDK_INT;

//    // 因为该方法在 Android 4.4 版本才可使用，所以使用时需进行版本判断
//    public void sendToJsWithParam(String param) {
//        Logger.i(TAG,"sendToJsWithParam is " + param);
////        ToastUtils.showToast(activity,"sendToJsWithParam is " + param);
//        WebView webContent = ((MainActivity) activity).getWebContent();
//        if (version < 18) {
//            webContent.loadUrl("javascript:onLoginResult(" + param + ")");
//        } else {
//            webContent.evaluateJavascript("javascript:onLoginResult(" + param + ")", new ValueCallback<String>() {
//                @Override
//                public void onReceiveValue(String value) {
//                    //此处为 js 返回的结果
//                    Logger.i(TAG, "onReceiveValue : value" + value);
//                }
//            });
//        }
//    }

    public void sendToJsWithParamWithFunction(String param,String JSFunction) {
        Logger.i(TAG, "sendToJsWithParamWithFunction is " + param);
        WebView webContent = ((MainActivity) activity).getWebContent();
        if (Build.VERSION.SDK_INT < 18) {
            webContent.loadUrl("javascript:"+JSFunction+"(" + param + ")");
        } else {
            webContent.evaluateJavascript("javascript:"+JSFunction+"(" + param + ")", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //此处为 js 返回的结果
                    Logger.i(TAG, "onAvatarUploadResult : value" + value);
                }
            });
        }
    }

    //here to recieve choose photo
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleChoose(Object msg) {
        EventCenter event = (EventCenter) msg;
        if (event.getResultCode() == Constant.MESSAGE_CHOOSE_PHOTO){
            String[] fileUris = (String[]) event.getMsg();
            behavior.doUpLoadFile(extra ,fileUris);
        }
    }
}
